package news.paper.tintuc.tinnong.docbao.doctin.GCM;

import news.paper.tintuc.tinnong.docbao.doctin.AppController;
import news.paper.tintuc.tinnong.docbao.doctin.R;
import news.paper.tintuc.tinnong.docbao.doctin.controller.ApiParams;
import news.paper.tintuc.tinnong.docbao.doctin.controller.RequestListener;
import news.paper.tintuc.tinnong.docbao.doctin.util.Constrant;

import org.json.JSONObject;

import tienich360.com.lib.JsonConvert;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class PopupAD {
	public static int ShowAdPopup = 0;
	public static int ShowAd = 0;
	public static int VersionUpdate;

	public static int IsUpdate = 0;
	public static String LinkUpdate = "";

	public static PopupInfo popupInfo;
	private MainCountDown countDown;

	private long timeshow = 20000;

	public void show_popupad(long time, Activity activity_) {
		timeshow = time;
		if (ShowAdPopup == 1) {
			if (popupInfo.getIsShowInstalled() == 1) {
				countDown = new MainCountDown(timeshow, timeshow, popupInfo,
						activity_);
				countDown.start();
			} else {
				boolean check = Constrant.isAppInstalled(
						activity_.getBaseContext(), popupInfo.getPackagename());
				if (!check) {
					countDown = new MainCountDown(timeshow, timeshow,
							popupInfo, activity_);
					countDown.start();
				}
			}

		}
	}

	public void show_popupad(Activity activity_) {
		new MainCountDown(timeshow, timeshow, popupInfo, activity_);
	}

	public void getAppinfo(final String PackageName,
			final RequestListener listener) {
		listener.begin();
		ApiParams apiParams = new ApiParams(
				"http://appmanage.tienich360.com/Service/AppManageService.asmx/getAppInfo?");
		apiParams.init();
		apiParams.addParams("PackageName", PackageName);
		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
				apiParams.toString(), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						try {
							JSONObject object_request = response
									.getJSONObject("request");
							int code = object_request.getInt("code");
							if (code == 1) {
								JSONObject object_appinfo = response
										.getJSONObject("appinfo");
								ShowAd = object_appinfo.getInt("ShowAd");
								ShowAdPopup = object_appinfo
										.getInt("ShowAdPopup");
								IsUpdate = object_appinfo.getInt("IsUpdate");
								if (IsUpdate == 1) {
									VersionUpdate = object_appinfo
											.getInt("VersionUpdate");
									LinkUpdate = object_appinfo
											.getString("LinkUpdate");
								}
								JSONObject object_adinfo = response
										.getJSONObject("adinfo");
								popupInfo = JsonConvert.DeserializeObject(
										PopupInfo.class, object_adinfo);
								listener.success(response);
							}
						} catch (Exception e) {
							e.printStackTrace();
							listener.fail(e.getMessage());
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						listener.fail(error.getMessage());
					}
				}) {
		};
		AppController.getInstance().addToRequestQueue(jsonObjReq);
	}

	public class MainCountDown extends CountDownTimer {
		private PopupInfo popupInfo;
		private Activity activity;

		public MainCountDown(long millisInFuture, long countDownInterval,
				PopupInfo popupInfo_, Activity activity_) {
			super(millisInFuture, countDownInterval);
			popupInfo = popupInfo_;
			activity = activity_;
		}

		@Override
		public void onFinish() {
			try {
				showAD_Image(activity, popupInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onTick(long millisUntilFinished) {
		}
	}

	public boolean showUpdate(Activity activity) {
		try {
			return (VersionUpdate > activity.getPackageManager()
					.getPackageInfo(activity.getPackageName(), 0).versionCode);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public void showPopupUpDate(final Activity activity) {
		AlertDialog.Builder ab = new AlertDialog.Builder(activity);
		ab.setCancelable(false);
		ab.setMessage("Bạn phải cập nhật ứng dụng trước khi sử dụng");
		ab.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(LinkUpdate));
					activity.startActivity(intent);
					activity.finish();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		ab.show();
	}

	public void showAD_Image(final Activity activity, final PopupInfo adPopup) {
		try {
			final AlertDialog.Builder gift = new AlertDialog.Builder(activity);
			final ImageView numb = new ImageView(activity);
			numb.setScaleType(ImageView.ScaleType.FIT_XY);
			DisplayImageOptions options = new DisplayImageOptions.Builder()
					.showImageOnLoading(R.drawable.null2)
					.showImageForEmptyUri(R.drawable.null2)
					.showImageOnFail(R.drawable.null2).cacheInMemory(true)
					.cacheOnDisk(true).considerExifParams(true)
					.bitmapConfig(Bitmap.Config.RGB_565).build();
			ImageLoader.getInstance().displayImage(adPopup.getLinkImage(),
					numb, options);

			gift.setTitle(adPopup.getTitle());
			gift.setView(numb);
			gift.setCancelable(true);
			numb.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					try {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri.parse(adPopup.getLink()));
						activity.startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			gift.setPositiveButton("Đồng ý",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							try {
								Intent intent = new Intent(Intent.ACTION_VIEW);
								intent.setData(Uri.parse(adPopup.getLink()));
								activity.startActivity(intent);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
			gift.setNegativeButton("Trở lại",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
			gift.create();
			gift.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
